package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.constatns.MqConstants;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.ItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



@Service("itemservice")
public class itemServiceImpl extends ServiceImpl<ItemMapper, Item> implements ItemService {

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;



    @Override
    public PageDTO<Item> selectItem(Integer page, Integer size) {

        Page<Item> itemPage = new Page<>(page, size);

        itemMapper.selectPage(itemPage,null);

        PageDTO<Item> pageDTO = new PageDTO<>(itemPage.getTotal(), itemPage.getRecords());

        return pageDTO;
    }

    @Override
    public Item queryItemByid(Long id) {
        Item item = itemMapper.selectById(id);
        return item;
    }

    @Override
    public void insertItem(Item item) {
      itemMapper.insert(item);
    }

    @Override
    public void updateItem(Long id, Integer status) {
        if(status==1){
            LambdaUpdateWrapper<Item> wrapper = Wrappers.lambdaUpdate(Item.class);
            wrapper.eq(Item::getId,id).set(Item::getStatus,status);
            itemMapper.update(null,wrapper);
            rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_INSERT_KEY,id);
        }else if(status==2){
            LambdaUpdateWrapper<Item> wrapper = Wrappers.lambdaUpdate(Item.class);
            wrapper.eq(Item::getId,id).set(Item::getStatus,status);
            itemMapper.update(null,wrapper);
            rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_DELETE_KEY,id);
        }
    }

    @Override
    public void upDateItem(Item item) {
        LambdaUpdateWrapper<Item> wrapper = Wrappers.lambdaUpdate(Item.class);
        wrapper.eq(Item::getId,item.getId());
        itemMapper.update(item,wrapper);
    }

    @Override
    public void deleteItem(Long id) {
        itemMapper.deleteById(id);
    }


    @Override
    public void jianInventory(Long itemId, Integer num) {
        Item item = itemMapper.selectById(itemId);
        Integer status = item.getStatus();
         Integer status1 = status - num;
        LambdaUpdateWrapper<Item> wrapper = Wrappers.lambdaUpdate(Item.class);
        wrapper.eq(Item::getId,itemId).set(Item::getStatus,status1);
        itemMapper.update(null,wrapper);

    }
}
